import pandas as pd
from datetime import datetime
import os
import sys

# 添加父目录到系统路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

# 使用普通导入（不依赖src包）
from quantitative.quant_factory import QuantAnalyzerFactory

class EnhancedStrategyGenerator:
    """增强版策略生成器，支持选择不同的量化框架"""
    
    def __init__(self, config):
        self.config = config
        self.quant_factory = QuantAnalyzerFactory(config)
        self.default_analyzer = config.get('default_analyzer', 'hikyuu')
        
    def generate_short_term_strategy(self, stock_code, tech_analysis, analyzer_type=None):
        """生成短期策略（1-5天）"""
        if analyzer_type is None:
            analyzer_type = self.default_analyzer
            
        analyzer = self.quant_factory.get_analyzer(analyzer_type)
        
        if analyzer_type == 'qlib':
            # 使用Qlib生成短期策略
            qlib_analysis = analyzer.get_market_analysis(stock_code, days=30)
            
            signals = []
            
            # 检查预测收益率
            if qlib_analysis['predicted_return_1d'] > 0.01:  # 预测1天收益率大于1%
                signals.append({
                    'signal': 'buy',
                    'strength': 'strong',
                    'reason': f'Qlib模型预测未来1天收益率为{qlib_analysis["predicted_return_1d"]*100:.2f}%，看多信号',
                    'timeframe': 'short'
                })
            elif qlib_analysis['predicted_return_1d'] < -0.01:  # 预测1天收益率小于-1%
                signals.append({
                    'signal': 'sell',
                    'strength': 'strong',
                    'reason': f'Qlib模型预测未来1天收益率为{qlib_analysis["predicted_return_1d"]*100:.2f}%，看空信号',
                    'timeframe': 'short'
                })
                
            # 检查MACD指标
            if qlib_analysis['macd_hist'] > 0 and qlib_analysis['macd_hist'] > qlib_analysis['macd_hist'] * 1.1:
                signals.append({
                    'signal': 'buy',
                    'strength': 'medium',
                    'reason': 'MACD柱线为正且持续增长，上升动能强',
                    'timeframe': 'short'
                })
                
            # 检查均线
            if qlib_analysis['ma5'] > qlib_analysis['ma10'] > qlib_analysis['ma20']:
                signals.append({
                    'signal': 'buy',
                    'strength': 'medium',
                    'reason': '均线多头排列，短期看涨',
                    'timeframe': 'short'
                })
                
        elif analyzer_type == 'hikyuu':
            # 使用Hikyuu生成短期策略
            hikyuu_analysis = analyzer.analyze_stock(stock_code)
            
            signals = []
            
            # 检查Hikyuu分析结果
            if "买入信号" in hikyuu_analysis['macd_signal']:
                signals.append({
                    'signal': 'buy',
                    'strength': 'strong',
                    'reason': f'MACD信号: {hikyuu_analysis["macd_signal"]}',
                    'timeframe': 'short'
                })
                
            if "买入信号" in hikyuu_analysis['kdj_signal']:
                signals.append({
                    'signal': 'buy',
                    'strength': 'medium',
                    'reason': f'KDJ信号: {hikyuu_analysis["kdj_signal"]}',
                    'timeframe': 'short'
                })
                
            if "超卖" in hikyuu_analysis['rsi_signal']:
                signals.append({
                    'signal': 'buy',
                    'strength': 'medium',
                    'reason': f'RSI信号: {hikyuu_analysis["rsi_signal"]}',
                    'timeframe': 'short'
                })
                
            if "卖出信号" in hikyuu_analysis['macd_signal']:
                signals.append({
                    'signal': 'sell',
                    'strength': 'strong',
                    'reason': f'MACD信号: {hikyuu_analysis["macd_signal"]}',
                    'timeframe': 'short'
                })
                
            if "超买" in hikyuu_analysis['rsi_signal']:
                signals.append({
                    'signal': 'sell',
                    'strength': 'medium',
                    'reason': f'RSI信号: {hikyuu_analysis["rsi_signal"]}',
                    'timeframe': 'short'
                })
        
        # 使用原有逻辑继续处理信号
        if not signals:
            # 使用原有技术分析结果作为备选
            if tech_analysis['MA_5'] > tech_analysis['MA_10'] and tech_analysis['trend'] == 'up':
                signals.append({
                    'signal': 'buy',
                    'strength': 'medium',
                    'reason': 'MA金叉且上升趋势确认',
                    'timeframe': 'short'
                })
            
            if 30 <= tech_analysis['RSI_6'] <= 40:
                signals.append({
                    'signal': 'buy',
                    'strength': 'medium',
                    'reason': 'RSI处于超卖区域，有反弹可能',
                    'timeframe': 'short'
                })
                
            if tech_analysis['MACD_hist'] > 0 and tech_analysis['MACD_hist_prev'] < 0:
                signals.append({
                    'signal': 'buy',
                    'strength': 'strong',
                    'reason': 'MACD柱线由负转正，买入信号',
                    'timeframe': 'short'
                })
                
        # 生成综合策略建议
        strategy = self._compile_strategy(signals, 'short')
        
        # 添加使用的分析器信息
        strategy['analyzer'] = analyzer_type
        
        return strategy
    
    def generate_medium_term_strategy(self, stock_code, tech_analysis, fundamental_analysis, analyzer_type=None):
        """生成中期策略（1-3个月）"""
        if analyzer_type is None:
            analyzer_type = self.default_analyzer
            
        analyzer = self.quant_factory.get_analyzer(analyzer_type)
        
        signals = []
        
        if analyzer_type == 'qlib':
            # 使用Qlib进行回测
            try:
                # 回测topk策略
                backtest_result = analyzer.backtest_strategy(
                    stock_code, 
                    (datetime.now() - pd.Timedelta(days=180)).strftime('%Y-%m-%d'),
                    datetime.now().strftime('%Y-%m-%d'),
                    'topk'
                )
                
                # 分析回测结果
                if backtest_result['report']['return'] > 0.05:  # 回测收益率大于5%
                    signals.append({
                        'signal': 'buy',
                        'strength': 'strong',
                        'reason': f'Qlib模型回测6个月收益率为{backtest_result["report"]["return"]*100:.2f}%，表现优秀',
                        'timeframe': 'medium'
                    })
            except Exception as e:
                # 如果回测失败，继续使用其他方法
                pass
                
        elif analyzer_type == 'hikyuu':
            # 使用Hikyuu的策略回测
            try:
                # 回测均线交叉策略
                backtest_result = analyzer.backtest(
                    stock_code,
                    (datetime.now() - pd.Timedelta(days=180)).strftime('%Y-%m-%d'),
                    datetime.now().strftime('%Y-%m-%d'),
                    'ma_cross'
                )
                
                # 分析回测结果
                if backtest_result['summary']['total_return'] > 5:  # 回测收益率大于5%
                    signals.append({
                        'signal': 'buy',
                        'strength': 'strong',
                        'reason': f'Hikyuu均线交叉策略回测6个月收益率为{backtest_result["summary"]["total_return"]:.2f}%，表现优秀',
                        'timeframe': 'medium'
                    })
                    
                # 胜率分析
                if backtest_result['summary']['win_rate'] > 60:  # 胜率大于60%
                    signals.append({
                        'signal': 'buy',
                        'strength': 'medium',
                        'reason': f'策略胜率{backtest_result["summary"]["win_rate"]:.2f}%，中期看好',
                        'timeframe': 'medium'
                    })
            except Exception as e:
                # 如果回测失败，继续使用其他方法
                pass
        
        # 使用原有逻辑继续处理信号
        if not signals:
            # 结合技术面和基本面分析
            if tech_analysis['trend'] == 'up' and fundamental_analysis['valuation'] == 'undervalued':
                signals.append({
                    'signal': 'buy',
                    'strength': 'strong',
                    'reason': '技术面趋势向上，且基本面估值偏低',
                    'timeframe': 'medium'
                })
            
            # 行业分析
            if fundamental_analysis['industry_outlook'] == 'positive':
                signals.append({
                    'signal': 'buy',
                    'strength': 'medium',
                    'reason': '所在行业前景良好',
                    'timeframe': 'medium'
                })
                
        # 生成综合策略建议
        strategy = self._compile_strategy(signals, 'medium')
        
        # 添加使用的分析器信息
        strategy['analyzer'] = analyzer_type
        
        return strategy
    
    def generate_long_term_strategy(self, stock_code, fundamental_analysis, analyzer_type=None):
        """生成长期策略（6个月以上）"""
        if analyzer_type is None:
            analyzer_type = self.default_analyzer
            
        analyzer = self.quant_factory.get_analyzer(analyzer_type)
        
        signals = []
        
        if analyzer_type == 'qlib':
            # 使用Qlib的长期回测
            try:
                # 回测topk策略
                backtest_result = analyzer.backtest_strategy(
                    stock_code, 
                    (datetime.now() - pd.Timedelta(days=365)).strftime('%Y-%m-%d'),
                    datetime.now().strftime('%Y-%m-%d'),
                    'topk'
                )
                
                # 分析回测结果
                if backtest_result['report']['return'] > 0.15:  # 回测年化收益率大于15%
                    signals.append({
                        'signal': 'buy',
                        'strength': 'strong',
                        'reason': f'Qlib模型回测1年收益率为{backtest_result["report"]["return"]*100:.2f}%，长期看好',
                        'timeframe': 'long'
                    })
            except Exception as e:
                # 如果回测失败，继续使用其他方法
                pass
                
        elif analyzer_type == 'hikyuu':
            # 使用Hikyuu的长期回测
            try:
                # 分别回测不同策略
                strategies = ['ma_cross', 'kdj_cross', 'macd_cross']
                best_return = 0
                best_strategy = ''
                
                for strategy in strategies:
                    backtest_result = analyzer.backtest(
                        stock_code,
                        (datetime.now() - pd.Timedelta(days=365)).strftime('%Y-%m-%d'),
                        datetime.now().strftime('%Y-%m-%d'),
                        strategy
                    )
                    
                    if backtest_result['summary']['total_return'] > best_return:
                        best_return = backtest_result['summary']['total_return']
                        best_strategy = strategy
                
                # 分析最佳回测结果
                if best_return > 15:  # 回测年化收益率大于15%
                    signals.append({
                        'signal': 'buy',
                        'strength': 'strong',
                        'reason': f'Hikyuu {best_strategy}策略回测1年收益率为{best_return:.2f}%，长期看好',
                        'timeframe': 'long'
                    })
            except Exception as e:
                # 如果回测失败，继续使用其他方法
                pass
        
        # 使用原有逻辑继续处理信号
        if not signals:
            # 主要基于基本面分析
            if fundamental_analysis['pe_ratio'] < fundamental_analysis['industry_avg_pe'] * 0.8:
                signals.append({
                    'signal': 'buy',
                    'strength': 'strong',
                    'reason': 'PE率显著低于行业平均',
                    'timeframe': 'long'
                })
            
            if fundamental_analysis['dividend_yield'] > 4.0:
                signals.append({
                    'signal': 'buy',
                    'strength': 'strong',
                    'reason': '高股息率股票，适合长期持有',
                    'timeframe': 'long'
                })
                
        # 生成综合策略建议
        strategy = self._compile_strategy(signals, 'long')
        
        # 添加使用的分析器信息
        strategy['analyzer'] = analyzer_type
        
        return strategy
    
    def _compile_strategy(self, signals, timeframe):
        """综合多个信号生成最终策略"""
        if not signals:
            return {
                'action': 'hold',
                'confidence': 'low',
                'reasoning': '无明确信号，建议观望',
                'timeframe': timeframe
            }
        
        # 计算买入卖出信号数量及强度
        buy_count = sum(1 for s in signals if s['signal'] == 'buy')
        sell_count = sum(1 for s in signals if s['signal'] == 'sell')
        
        buy_strength = sum(
            1.0 if s['strength'] == 'strong' else 0.5
            for s in signals if s['signal'] == 'buy'
        )
        
        sell_strength = sum(
            1.0 if s['strength'] == 'strong' else 0.5
            for s in signals if s['signal'] == 'sell'
        )
        
        # 决定最终行动
        if buy_strength > sell_strength:
            action = 'buy'
            strength = buy_strength
            reasons = [s['reason'] for s in signals if s['signal'] == 'buy']
        elif sell_strength > buy_strength:
            action = 'sell'
            strength = sell_strength
            reasons = [s['reason'] for s in signals if s['signal'] == 'sell']
        else:
            action = 'hold'
            strength = 0
            reasons = ['买卖信号强度相当，建议观望']
        
        # 计算置信度
        if strength >= 2:
            confidence = 'high'
        elif strength >= 1:
            confidence = 'medium'
        else:
            confidence = 'low'
            
        return {
            'action': action,
            'confidence': confidence,
            'reasoning': '; '.join(reasons),
            'timeframe': timeframe
        } 